package com.example.smartcity.ui.home.fragment

import android.graphics.Point
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.core.text.htmlEncode
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity.SmartCityApplication
import com.example.smartcity.databinding.FragmentFragment1Binding
import com.example.smartcity.logic.utils.Toast.Companion.showToast
import com.example.smartcity.ui.home.HomeViewModel
import com.example.smartcity.ui.home.adapter.NewSHotRecyclerViewAdapter
import com.example.smartcity.ui.home.model.NewSRecyclerViewEntity
import com.example.smartcity.ui.newS.NewsViewModel
import okhttp3.HttpUrl.Companion.toHttpUrl
import kotlin.concurrent.thread


class fragment1 : Fragment() {
    // 存储数据
    val listData = ArrayList<NewSRecyclerViewEntity>()


    private val newSViewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    private lateinit var mBinding: FragmentFragment1Binding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentFragment1Binding.inflate(inflater, container, false)

        // 设置新闻列表
        NewSData()


        return mBinding.root
    }


    /**
     * 获取新闻列表
     */
    fun NewSData(){
        repeat(1){
            // 设置RecyclerView适配器
            val layout = LinearLayoutManager(context)
            mBinding.HomeRecyclerView.layoutManager = layout
            val adapter = NewSHotRecyclerViewAdapter(listData)
            mBinding.HomeRecyclerView.adapter = adapter

            // 添加数据
            newSViewModel.newS(9)
            newSViewModel.newSLiveData.observe(this) { resources ->
                val body =  resources.getOrNull()
                if(body != null){
                    // 清空数据
                    newSViewModel.newSList.clear()
                    // 添加数据
                    newSViewModel.newSList.addAll(body)
                }

                // 设置数据
                for(i in newSViewModel.newSList){
                    val size = newSViewModel.newSList.size
                    if(listData.size < size){
                        listData.add(NewSRecyclerViewEntity(
                            SmartCityApplication.url + i.cover,
                            i.title,
                            Html.fromHtml(i.content).toString(),
                            i.commentNum.toString() + "评论",
                            i.publishDate))
                        adapter.notifyItemChanged(listData.size)
                    } else break
                }
            }
        }

    }
}